<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface
{

    // 这个变量用来跟踪用户申请成为律师的流程
    const STATUS_USER = 1;                  // 普通用户
    const STATUS_BECOMING_LAWYER = 2;       // 用户提交了成为律师的申请
    const STATUS_VERIFIED_LAWYER = 3;       // 用户称为了经过审查的律师

    const USER_GROUP_USER = 1;
    const USER_GROUP_LAWYER = 2;

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'user';

    /**
     * 软删除
     * @var boolean
     */
    protected $softDelete = true;

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    public function group()
    {
        return $this->belongsTo('UserGroup', 'user_group_id');
    }

    /**
     * 调整器：密码
     * @param  string $value 未处理的密码字符串
     * @return void
     */
    public function setPasswordAttribute($value)
    {
        // 若传入的字符串已经进行了 Hash 加密，则不重复处理
        $this->attributes['password'] = Hash::needsRehash($value) ? Hash::make($value) : $value;
    }

    public function getRememberToken()
    {
        return $this->remember_token;
    }

    public function setRememberToken($value)
    {
        $this->remember_token = $value;
    }

    public function getRememberTokenName()
    {
        return 'remember_token';
    }

    public static function user_name($id)
    {
        if (Auth::check()) {
            $customer = Customer::find($id);
            if ($customer) {
                return $customer->realname;
            }
            $company = Company::find($id);
            if ($company) {
                return $company->name;
            }
            $lawyer = Lawyer::find($id);
            if ($lawyer) {
                return $lawyer->realname;
            }

        } else {
            return '';
        }
    }

    public function realname()
    {
        $model = $this->group->model;
        $attrname = $model == 'Company' ? 'name' : 'realname';

        return App::make($model)->find($this->id)->$attrname;
    }

    public function lawyer()
    {
        return $this->hasOne('Lawyer', 'user_id');
    }

    public function isPendingVerification()
    {
        return ($this->status == self::STATUS_BECOMING_LAWYER);
    }

    public function isVerifiedLawyer()
    {
        return ($this->status == self::STATUS_VERIFIED_LAWYER);
    }

    public function isLiked()
    {
        $is_liked = Like::where('item_id', $this->id)->where('like_type', Like::TYPE_USER)->where('creator_id', Auth::user()->id)->first();

        return (bool)$is_liked;
    }

    public function comments()
    {
        return $this->hasMany('Comment', 'creator_id');
    }

    public function collectedLawyers()
    {
        return $this->hasMany('Collect', 'creator_id');
    }

    public function questions()
    {
        return $this->hasMany('Post', 'creator_id')->where('type', '=', Post::TYPE_QUESTION);
    }

    public function orders()
    {
        return $this->hasMany('Order', 'user_id');
    }

    public function articles()
    {
        $querycondition = ['from_admin' => 0, 'Stauts' => '1'];

        return Article::where($querycondition);
    }

    // 经典案例
    public function cases()
    {
        return $this->hasMany('Post', 'creator_id')->where('type', '=', Post::TYPE_LAWSUIT);
    }

    public function scopeOfProvinceId($query, $province_id)
    {
        if ($province_id) {
            $query = $query->whereProvince($province_id);
        }

        return $query;
    }

    public function scopeOfCityId($query, $city_id)
    {
        if ($city_id) {
            $query = $query->whereCity($city_id);
        }

        return $query;
    }

    public function scopeOfDistrictId($query, $district_id)
    {
        if ($district_id) {
            $query = $query->whereDistrict($district_id);
        }

        return $query;
    }

    public function scopeOfSearch($query, $search)
    {
        if ($search) {
            $query = $query->where('realname', 'like', "%$search%");
        }

        return $query;
    }

    public function scopeOfIsRecommended($query, $is_recommended)
    {
        if ($is_recommended) {
            $query = $query->where('lawyer.is_recommended', '=', $is_recommended);
        }

        return $query;
    }

    public function scopeOfCreatedAt($query, $created_at)
    {
        if ($created_at) {
            $query = $query->where('user.created_at', '>=', $created_at);
        }

        return $query;
    }

    protected static function addLawyerIfNotExist($user)
    {
        $user->load('lawyer');
        if (!$user->lawyer) {
            $lawyer = new Lawyer();
            $lawyer->user_id = $user->id;
            $lawyer->save();
        }
    }

    /*
     * license
     * license_file
     * company_name
     * practice_period
     * address
     *
     * 增改用户的从业信息
     */
    public static function addOrUpdateLawyerWorkInfo($id, $data)
    {
        $user = User::find($id);
        self::addLawyerIfNotExist($user);

        $user->load('lawyer');
        if (isset($data['province'])) {
            $user->province = $data['province'];                            // 省份
        }
        if (isset($data['city'])) {
            $user->city = $data['city'];                            // 城市
        }
        if (isset($data['district'])) {
            $user->district = $data['district'];                            // 地区
        }
        // 执业证号和执业证书在还没有提交的时候是可以更改的
        if ($user->status == self::STATUS_USER) {
            if (isset($data['license'])) {
                $user->lawyer->license = $data['license'];                  // 执业证号
            }
            if (isset($data['license_file'])) {
                $user->lawyer->license_file = UploadHelper::preprocessUploadFilePath($data['license_file']);  // 执业证书
            }
        }
        if (isset($data['company_name'])) {
            $user->lawyer->company_name = $data['company_name'];            // 执业机构
        }
        if (isset($data['practice_period'])) {
            $user->lawyer->practice_period = $data['practice_period'];      // 执业年限
        }
        DB::transaction(function () use ($user) {
            $user->save();
            $user->lawyer->save();
        });

        return $user;
    }

    /*
     * realname
     * ID_img
     *
     * 增改用户的实名认证信息
     */
    public static function addOrUpdateLawyerIdentityInfo($id, $data)
    {
        $user = User::find($id);
        self::addLawyerIfNotExist($user);

        $user->load('lawyer');
        // 执业证号和执业证书在还没有提交的时候是可以更改的
        if ($user->status == self::STATUS_USER) {
            if (isset($data['realname'])) {
                $user->realname = $data['realname'];                        // 真实姓名
            }
            if (isset($data['ID_img'])) {
                $user->lawyer->ID_img = UploadHelper::preprocessUploadFilePath($data['ID_img']);  // 身份证
            }
        }
        DB::transaction(function () use ($user) {
            $user->save();
            $user->lawyer->save();
        });

        return $user;
    }

    /*
     * text_reply_fee
     * phone_reply_fee
     *
     * 增改用户的资费信息
     */
    public static function addOrUpdateLawyerFeeInfo($id, $data)
    {
        $user = User::find($id);
        self::addLawyerIfNotExist($user);

        $user->load('lawyer');
        if (isset($data['text_reply_fee'])) {
            $user->lawyer->text_reply_fee = $data['text_reply_fee'];   // 图文咨询资费
        }
        if (isset($data['phone_reply_fee'])) {
            $user->lawyer->phone_reply_fee = $data['phone_reply_fee'];   // 电话咨询资费
        }
        $user->lawyer->save();

        return $user;
    }

    /*
     * work_scope
     *
     * 增改用户的擅长领域信息
     */
    public static function addOrUpdateLawyerWorkscopeInfo($id, $data)
    {
        $user = User::find($id);
        self::addLawyerIfNotExist($user);

        $user->load('lawyer');
        if (isset($data['work_scope'])) {
            $user->lawyer->work_scope = implode(",", $data['work_scope']);        // 工作范围
        }
        $user->lawyer->save();

        return $user;
    }

    /*
     * introduce
     * experience
     * law_cases
     *
     * 增改用户的经历案例信息
     */
    public static function addOrUpdateLawyerExperienceInfo($id, $data)
    {
        $user = User::find($id);
        self::addLawyerIfNotExist($user);

        $user->load('lawyer');
        if (isset($data['introduce'])) {
            $user->lawyer->introduce = $data['introduce'];
        }
        if (isset($data['experience'])) {
            $user->lawyer->experience = $data['experience'];
        }
        if (isset($data['law_cases'])) {
            $user->lawyer->law_cases = $data['law_cases'];
        }
        $user->lawyer->save();

        return $user;
    }

    public static function becomeLawyer($id)
    {
        $user = User::find($id);
        $user->status = self::STATUS_BECOMING_LAWYER;
        $user->user_group_id = self::USER_GROUP_LAWYER;
        $user->save();

        return $user;
    }

    /**
     * 用户成为律师
     *
     * @param id
     * @param data
     */
    public static function addLawyer($id, $data)
    {
        $user = User::find($id);
        $user->realname = $data['realname'];            // 姓名
        $user->sex = isset($data['sex']) ? $data['sex'] : null;                      // 性别
        $user->province = $data['province'];            // 省
        $user->city = $data['city'];                    // 市
        $user->district = $data['district'];            // 区
        $user->address = isset($data['address']) ? $data['address'] : null;              // 地址
        if (isset($data['avatar'])) {
            $user->avatar = UploadHelper::preprocessUploadFilePath($data['avatar']);                // 头像
        }
        $user->signature = isset($data['signature']) ? $data['signature'] : null;          // 个性签名
        $user->status = self::STATUS_BECOMING_LAWYER;
        $user->user_group_id = self::USER_GROUP_LAWYER;

        $user->load('lawyer');
        if (!$user->lawyer) {
            $lawyer = new Lawyer();
            $lawyer->user_id = $user->id;
        } else {
            $lawyer = $user->lawyer;
        }
        $lawyer->license = $data['license'];            // 律师证号
        $lawyer->license_file = UploadHelper::preprocessUploadFilePath($data['license_file']);  // 律师证路径
        $lawyer->ID_img = UploadHelper::preprocessUploadFilePath($data['ID_img']);            // 身份证路径
        if (isset($data['bg_image'])) {
            $lawyer->bg_image = UploadHelper::preprocessUploadFilePath($data['bg_image']);          // 背景图片
        }
        $lawyer->practice_period = isset($data['practice_period']) ? $data['practice_period'] : null;  // 工作年限
        $lawyer->introduce = isset($data['introduce']) ? $data['introduce'] : null;          // 个人简历
        $lawyer->experience = isset($data['experience']) ? $data['experience'] : null;        // 个人经历
        $lawyer->law_cases = isset($data['law_cases']) ? $data['law_cases'] : null;          // 成功案例
        $lawyer->work_scope = isset($data['work_scope']) ? implode(",", $data['work_scope']) : null;        // 工作范围
        $lawyer->company_name = $data['company_name'];    // 执业机构
        $lawyer->position = isset($data['position']) ? $data['position'] : null;            // 律师类型
        $lawyer->text_reply_fee = $data['text_reply_fee'];   // 图文咨询价格
        $lawyer->phone_reply_fee = $data['phone_reply_fee'];  // 语音咨询价格

        DB::transaction(function () use ($user, $lawyer) {
            $user->save();
            $lawyer->save();
        });

        return $user;
    }

    /**
     * 更新律师信息
     *
     * @param id
     * @param data
     */
    public static function updateLawyer($id, $data)
    {
        $user = User::find($id);
        $user->load('lawyer');

        if (isset($data['realname'])) {
            $user->realname = $data['realname'];
        }
        if (isset($data['nikname'])) {
            $user->nikname = $data['nikname'];
        }
        if (isset($data['sex'])) {
            $user->sex = $data['sex'];
        }
        if (isset($data['province'])) {
            $user->province = $data['province'];
        }
        if (isset($data['city'])) {
            $user->city = $data['city'];
        }
        if (isset($data['district'])) {
            $user->district = $data['district'];
        }
        if (isset($data['address'])) {
            $user->address = $data['address'];
        }
        if (isset($data['avatar'])) {
            $user->avatar = UploadHelper::preprocessUploadFilePath($data['avatar']);
        }
        if (isset($data['signature'])) {
            $user->signature = $data['signature'];
        }

        // 更新律师相关信息
        if (isset($data['company_name'])) {
            $user->lawyer->company_name = $data['company_name'];
        }
        if (isset($data['bg_image'])) {
            $user->lawyer->bg_image = UploadHelper::preprocessUploadFilePath($data['bg_image']);
        }
        if (isset($data['practice_period'])) {
            $user->lawyer->practice_period = $data['practice_period'];
        }
        if (isset($data['introduce'])) {
            $user->lawyer->introduce = $data['introduce'];
        }
        if (isset($data['experience'])) {
            $user->lawyer->experience = $data['experience'];
        }       // 个人简历
        if (isset($data['law_cases'])) {
            $user->lawyer->law_cases = $data['law_cases'];
        }    // 成功案例
        if (isset($data['work_scope'])) {
            $user->lawyer->work_scope = implode(",", $data['work_scope']);
        }    // 工作范围
        if (isset($data['position'])) {
            $user->lawyer->position = $data['position'];
        }    // 律师类型
        if (isset($data['text_reply_fee'])) {
            $user->lawyer->text_reply_fee = $data['text_reply_fee'];   // 图文咨询价格
        }
        if (isset($data['phone_reply_fee'])) {
            $user->lawyer->phone_reply_fee = $data['phone_reply_fee'];  // 语音咨询价格
        }

        DB::transaction(function () use ($user) {
            $user->lawyer->save();
            $user->save();
        });

        return $user;
    }

    public function addWxUser($username, $password, $account_type, $wx_openid)
    {

    }

    public static function addUser($username, $password, $account_type, $wx_openid, $active = 0)
    {
        $user = new User ();
        if ($account_type == 'phone') {
            $user->phone = $username;
        } else {
            $user->email = $username;
        }
        $user->nikname = '匿名';
        $user->password = $password;
        $user->account = $username;
        $user->score = 0;
        $user->likes_count = 0;
        $user->collects_count = 0;
        $user->active = $active;
        $user->indie = 1;
        $user->user_group_id = 1;
        $user->status = self::STATUS_USER;
        $user->save();
        $group = UserGroup::where('id', $user->user_group_id)->firstOrFail();
        $model_name = $group->model;
        $user_model = new $model_name ();
        $user_model->user_id = $user->id;
        $user_model->save();

        // 这个lawyer对象只是作为一个placeholder
        $lawyer = new Lawyer();
        $lawyer->user_id = $user->id;
        $lawyer->save();

        return $user;
    }

	/**
     * @param $user_info
     * @param null $type
     * @return User
     */
    public static function addUserWithWxUnionId($user_info, $type = 'wx')
    {
        $user = new User ();
        /**
         * 检查用户是否存在
         */
        if($type == 'wx'){
            $union_id = $user_info['union_id'];
        }else{
            $union_id = $user_info['open_id'];
        }
        $user = $user->where('union_id', $union_id)->first();
        if (empty($user)) {
            $user = new User ();
            $user->score = 0;
            $user->likes_count = 0;
            $user->collects_count = 0;
            $user->active = 0;
            $user->indie = 1;
            $user->user_group_id = 1;
            $user->active = 1;

            if($type == 'wx'){
                $user->union_id = $union_id;
            }elseif($type == 'qq'){
                $user->qq_openid = $union_id;
            }

            $user->save();
            // $user->invitor = $uid;
            $user->user_group_id = 1;
            $group = UserGroup::where('id', $user->user_group_id)->firstOrFail();
            $model_name = $group->model;
            $user_model = new $model_name ();
            $user_model->user_id = $user->id;
            $user_model->save();
        }

        return $user;
    }

    /**
     * 更新普通用户信息
     *
     * @param id
     * @param data
     */
    public static function updateUser($id, $data)
    {
        $user = User::find($id);
        if (isset($data['phone'])) {
            $user->phone = $data['phone'];
        }
        if (isset($data['realname'])) {
            $user->realname = $data['realname'];
        }
        if (isset($data['nikname'])) {
            $user->nikname = $data['nikname'];
        }
        if (isset($data['sex'])) {
            $user->sex = $data['sex'];
        }
        if (isset($data['province'])) {
            $user->province = $data['province'];
        }
        if (isset($data['city'])) {
            $user->city = $data['city'];
        }
        if (isset($data['district'])) {
            $user->district = $data['district'];
        }
        if (isset($data['address'])) {
            $user->address = $data['address'];
        }
        if (isset($data['avatar'])) {
            $user->avatar = UploadHelper::preprocessUploadFilePath($data['avatar']);
        }
        if (isset($data['signature'])) {
            $user->signature = $data['signature'];
        }

        DB::transaction(function () use ($user) {
            $user->save();
        });

        return $user;
    }

    public static function resetPass($id, $data)
    {
        $user = User::find($id);
    }

    public function getUserName()
    {
        return $user_name = $this->realname ? $this->realname : substr_replace($this->phone, '****', 3, 4);
    }

    public static function getByUsername($username)
    {
        return self::where('account', $username)->firstOrFail();
    }

    public static function getByOpenId($openid)
    {
        return self::where('wx_openid', $openid)->firstOrFail();
    }

    public static function getByUnionId($union_id, $platform)
    {
        if($platform == 'wx'){
            $column = 'union_id';
        }else{
            $column = 'qq_openid';

        }
        return self::where($column, $union_id)->first();
    }
}
